<template>
    <div>
        <NavTop></NavTop>
        <div style="width: 1400px; margin: auto">
        <el-table
            ref="multipleTableRef"
            :data="filterTableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" :selectable="selectable" width="55" />
            
            <el-table-column property="id" label="商品编号" width="120" />
            <el-table-column property="name" label="商品名称" width="520" />
            <el-table-column property="onlinePrice" label="价格" width="120" />
            <el-table-column property="num" label="数量" width="120" />
            <el-table-column property="total" label="总金额" width="120" />
           
            <el-table-column align="right">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="Type to search" />
                </template>
            <template #default="scope">
                <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >
                删除
                </el-button>
            </template>
            </el-table-column>
        </el-table>
        <div style="margin: auto;">
          <el-button @click="buy()">
          购买
        </el-button>
        </div>
    </div>
</div>
</template>


<script>
import NavTop from '@/components/NavTop.vue';
import {useGoodsStore} from '../../store/goods';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from "@/router";
import { ElNotification } from 'element-plus'


export default {
    components:{
        NavTop,
    },
    data() {
        return {
            multipleTableRef:null,
            multipleSelection :[],
            store:useGoodsStore(),
            cartData:JSON.parse(sessionStorage.getItem('cart')),
            time:new Date(),
            orderId:'',
            search:'',    
        }
    },
    mounted() {
        if (sessionStorage.getItem('username') == null || sessionStorage.getItem('username') =='游客' ) {
            this.open()
            router.push('/login');
        } 
        
    },
    methods: {
        open(){
            ElNotification({
            title: '请登录',
            message: '你知道的，不是我不想给你看',
            type: 'error',
         })
        },
        handleSelectionChange(val){
            this.multipleSelection = val
        },
        handleDelete(index){
            ElMessageBox.confirm(
            '那我问你，那我问你',
            'Warning',
            {
            confirmButtonText: '对的对的',
            cancelButtonText: '实则不然',
            type: 'warning',
            }
        )
            .then(() => {
            ElMessage({
                type: 'warning',
                message: '你杀死了一小撮代码！！！',
            })
            this.cartData.splice(index,1)
            sessionStorage.setItem('cart',JSON.stringify(this.cartData))
            })
            .catch(() => {
            ElMessage({
                type: 'success',
                message: '感谢您的善良',
            })
            })
          
        },
        buy(){
            if(this.multipleSelection==''){
                ElMessageBox.alert('你很急吗？不急的话就把这一串话看完吧，虽然没什么用，这只是一个小通知，不征求你的同意,因为你根本没买东西', '就卡你一下，就卡你就卡你', {
                confirmButtonText: '不急',
            })
            }
            else{
            ElMessageBox.alert('你很急吗？不急的话就把这一串话看完吧，虽然没什么用，这只是一个小通知，不征求你的同意', '就卡你一下，就卡你就卡你', {
                confirmButtonText: '不急',
            })
        //订单号
        this.orderId=this.time.getFullYear().toString() +(this.time.getMonth()+1).toString()+
        this.time.getDate().toString()+Math.random().toString().slice(2,10)
          console.log(this.orderId);
          let num =0
          let sum =0
          //从选中的商品中进行便利循环，把每个商品的数量和金额进行相加
          this.multipleSelection.map(v=>{
              num += v.num
              sum += parseInt(v.total)
          })
          console.log(num);
          console.log(sum);
          //把相关的数据添加到store中的订单数组里
          this.store.orderAdd({
            orderId:this.orderId,
            time:this.time,
            num:num,
            sum:sum,
            isOrdered:false,        //这个变量用来记录订单是否已经完成支付
            child:[...this.multipleSelection]///展开运算符把一个数组逐一进行操作，相当于进行了循环
          })
          console.log(this.store.orderData);


        //商品加入订单后要在购物车中进行删除
          this.multipleSelection.forEach((list )=> {
            let x =this.cartData.findIndex((item)=>list.id == item.id)
            this.cartData.splice(x,1)
            sessionStorage.setItem('cart',JSON.stringify(this.cartData))
        });
        }
    }
       
      
    },
    computed:{
        filterTableData(){
            if(this.cartData==null){
                return this.data
            }else{
            return this.cartData.filter(item => {
                return this.search.toLowerCase().split('').every(keyword=> {
                    return item.name.toLowerCase().includes(keyword) ||item.id.toString().includes(keyword)
                })
            })
        }
        }      
    },

}
</script>